<template>
  <div class="menu-wrapper">
    <el-form ref="form" :model="form" :rules="rules" label-width="140px">
      <div
        style="width: 100%;display: flex;align-items: flex-end;border-bottom: 1px #eee solid;margin-bottom: 20px"
      >
        <span style="font-size: 18px;color:#409EFF;margin: 10px 0;">基本信息</span>
      </div>

      <el-form-item label="司机姓名:" prop="name">
        <el-col :span="6">
          <el-input v-model="form.name" clearable placeholder="请输入司机姓名"/>
        </el-col>
      </el-form-item>
      <el-form-item label="联系方式:" prop="phone">
        <el-col :span="6">
          <el-input type="tel" v-model.number="form.phone" @input="val = String(val).replace(/[^\d]/g,'')" clearable
                    placeholder="请输入司机联系方式"/>
        </el-col>
      </el-form-item>
      <el-form-item label="车牌号:" prop="plate">
        <el-col :span="6">
          <el-input v-model="form.plate" placeholder="请输入车牌号"/>
        </el-col>
      </el-form-item>
      <el-form-item label="所属账户:" prop="companyId">
        <el-col :span="6">
          <query-company @queryCompanyClick='queryCompanyClick' :companyId="form.companyId"  :name="form.companyName"/>
        </el-col>
      </el-form-item>

      <div style="width: 100%;display: flex;align-items: flex-end;border-bottom: 1px #eee solid;margin-bottom: 20px">
        <span style="font-size: 18px;color:#409EFF;margin: 10px 0;">资质信息</span>
      </div>
      <el-form-item label="身份证号:" prop="idNo">
        <el-col :span="6">
          <el-input v-model="form.idNo" clearable placeholder="请输入司机身份证号"/>
        </el-col>
      </el-form-item>
      <el-form-item label="身份证国徽面:" prop="legalPerson1">
        <singleUpload :singleUploadTitle="singleUploadTitle" v-model="form.metaInfo.legalPerson1"
                      style="display: inline-block;  width: 500px" v-if="imgShow==true"></singleUpload>
        <img :src="form.metaInfo.legalPerson1" style="width:70px;height:70px" alt=""
             v-if="form.metaInfo.legalPerson1!=null&&imgShow==false">
        <span v-if="form.metaInfo.legalPerson1==null&&imgShow==false">{{ $t('sysMch.edit.noneAtPresent') }}</span>
      </el-form-item>
      <el-form-item label="身份证人像面:" prop="legalPerson2">
        <singleUpload :singleUploadTitle="singleUploadTitle" v-model="form.metaInfo.legalPerson2"
                      style="display: inline-block;  width: 500px" v-if="imgShow==true"></singleUpload>
        <img :src="form.metaInfo.legalPerson2" style="width:70px;height:70px" alt=""
             v-if="form.metaInfo.legalPerson2!=null&&imgShow==false">
        <span v-if="form.metaInfo.legalPerson2==null&&imgShow==false">{{ $t('sysMch.edit.noneAtPresent') }}</span>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" :loading="clicked"
                   @click="update('form')">保 存
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<style scoped>
.menu-wrapper {
  margin: 15px;
}
</style>
<script>
import {EventBus} from "@/api/eventBus";
import utils from "../../utils/utils.js";
import {update, find} from "@/api/car";
import md5 from "js-md5";
import QueryGroup from "@/components/Query/queryGroup";
import QueryCompany from "@/components/Query/queryCompany";
import Security from "@/views/customer/components/Security";
import officeDialog from '@/components/OfficeDialog'
import singleUpload from "@/components/Upload/singleUpload";
import multiUpload from "@/components/Upload/multiUpload";
import permission from "@/directive/permission/index.js";// 权限判断指令

export default {
  name: "vehicleManagement-edit",
  directives: {permission},

  filters: {},
  components: {
    Security,
    QueryGroup,
    QueryCompany,
    officeDialog,
    singleUpload,
    multiUpload
  },
  data() {
    const phone = (rule, value, callback) => {

      if (utils.isNull(value)) {
        callback(new Error('请输入手机号'));
      } else if (value.length < 11) {
        callback(new Error('请核对手机号'));
      } else if (!/^1(3|4|5|7|8)\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号'));
      } else {
        callback();
      }

    }
    var legalPerson1 = (rule, value, callback) => {
      if (utils.isNull(this.form.metaInfo.legalPerson1)) {
        callback(new Error('请上传身份证国徽面'));
      } else {
        callback();
      }
    }
    var legalPerson2 = (rule, value, callback) => {
      if (utils.isNull(this.form.metaInfo.legalPerson2)) {
        callback(new Error('请上传身份证人像面'));
      } else {
        callback();
      }
    }
    const ID = (rule, value, callback) => {
      let _IDRe18 = /^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
      let _IDre15 = /^([1-6][1-9]|50)\d{4}\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}$/
      // 校验身份证：
      if (_IDRe18.test(value) || _IDre15.test(value)) {
        callback();
      } else if (utils.isNull(value)) {
        callback(new Error('请输入身份证号'));
      } else {
        callback(new Error('请输入正确的身份证号'));
      }
    }
    return {
      pageNum: 1,
      pageSize: 20,
      imgShow: true,
      singleUploadTitle: "100*100",
      clicked: false, // 按钮防双击
      form: {
        id:null,
        name: "", //公司名称
        phone: "",  //联系电话
        plate: '',  //车牌号
        idNo: '', //身份证号
        companyId: '',    //所属账户
        // meta: "", //审核资料
        metaInfo: {
          legalPerson1: "", //正面（国徽）
          legalPerson2: "", //反面（人像）
          legalPersonCode: '',  //身份证号
        },
        status: 0,        //状态(0.未认证,1.已认证)
      },
      rules: {
        name: [
          {required: true, message: "请输入司机名称", trigger: "blur"},
          {min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur"}
        ],
        plate: [
          {required: true, message: "请输入车牌号", trigger: "blur"}
        ],
        phone: [
          {required: true, validator: phone, trigger: "blur"}
        ],
        companyId: [
          {required: true, message: "请选择所属账户", trigger: "blur"}
        ],
        idNo: [
          {required: true, validator: ID, trigger: "blur"}
        ],
        legalPerson1: [
          {required: true, validator: legalPerson1, trigger: "change"}
        ],
        legalPerson2: [
          {required: true, validator: legalPerson2, trigger: "blur"}
        ],
      },

    };
  },
  created() {
    var _this = this;
    _this.getData()
  },
  watch: {
    // 路由地址不变的情况下,如果id变化则重新获取数据
    $route(newVal, oldVal) {
      if (newVal.name == 'vehicleManagement-edit' && newVal.query.id != this.id) {
        this.getData()
      }
    },
    'form.metaInfo.legalPerson1': {
      handler(newVal, oldVal) {
        console.log(1)
        this.$refs.form.validateField('legalPerson1')
      }
    },
    'form.metaInfo.legalPerson2': {
      handler(newVal, oldVal) {
        this.$refs.form.validateField('legalPerson2')
      }
    },
    'form.companyName': {
      handler(newVal, oldVal) {
        this.$refs.form.validateField('companyName')
      }
    },
    'form.idNo': {
      handler(newVal, oldVal) {
        this.form.metaInfo.legalPersonCode = newVal
      }
    }
  },
  methods: {
    getData() {
      this.form.id = this.$route.query.id;
      var _this = this;
      find(_this.form.id)
        .then(response => {
          console.log(response, 'find')
          if (response.type == "success") {
            _this.form = response.data.car;
            _this.form.customerId = response.data.customer.id;
            _this.form.customerName = response.data.customer.name;
          } else {
            _this.$message({
              message: response.content,
              offset: 120,
              center: true
            });

          }
        })
        .catch(error => {
        });
    },

    queryCompanyClick(val) {
      // console.log("选择的是", val)
      this.form.companyId = val.companyId;
      this.form.companyName = val.name;
//      this.companyName = this.form.companyName
      console.log("选择的账户是", this.form.companyName)
    },
    queryGroupClick(val) {
      // console.log("选择的是", val)
      this.form.groupId = val.groupId
      this.form.groupName = val.name
//      this.groupName = this.form.groupName
      console.log("选择的集团是", this.form.groupName)
    },
    selectNature(e) {
      this.form.nature = e.id
    },

    update(form) {
      const _this = this;
      console.log("form", this.$refs[form].model);
      // console.log("点击创建了", this.$refs[form],)
      this.$refs[form].validate(valid => {
        console.log("点击创建了", valid)
        if (valid) {
          // 校验表单
          var list = {
            id: _this.form.id,
            name: _this.form.name,
            phone: _this.form.phone,
            plate: _this.form.plate,
            idNo: _this.form.idNo,
            companyId: _this.form.companyId,
            // meta: _this.form.meta,
            metaInfo: {
              legalPerson1: _this.form.metaInfo.legalPerson1,
              legalPerson2: _this.form.metaInfo.legalPerson2,
              legalPersonCode: _this.form.metaInfo.legalPersonCode
            },
            status: _this.form.status,
          }
          _this.clicked = true;
          console.log(list)
          update(list)
            .then(response => {
              _this.clicked = false;
              if (response.type == "success") {
                let data = response.data;
                console.log("修改完返回给列表的数据--" + JSON.stringify(data));
                EventBus.$emit("customer-add", data);
                _this.$store
                  .dispatch("tagsView/delView", _this.$route)
                  .then(({visitedViews}) => {
                    _this.$router.push({
                      path: "/vehicleManagement/list"
                    });
                  }); // 关闭当前tab回到列表
              } else {
                _this.$message({
                  message: response.content,
                  offset: 120,
                  center: true
                });
                console.log("content", response.content);

              }
            })
            .catch(error => {
              _this.clicked = false;
            });
        } else {
          return false;
        }
      });
    },
    //过滤成日期
    formatDate2Day(val) {
      let date = new Date(val);
      let y = date.getFullYear();
      let MM = date.getMonth() + 1;
      MM = MM < 10 ? "0" + MM : MM;
      let d = date.getDate();
      d = d < 10 ? "0" + d : d;
      return y + "-" + MM + "-" + d;
    },
    //过滤到时间
    formatDate2Time(val) {
      let date = new Date(val);
      let y = date.getFullYear();
      let MM = date.getMonth() + 1;
      MM = MM < 10 ? "0" + MM : MM;
      let d = date.getDate();
      d = d < 10 ? "0" + d : d;
      let h = date.getHours();
      h = h < 10 ? "0" + h : h;
      let m = date.getMinutes();
      m = m < 10 ? "0" + m : m;
      let s = date.getSeconds();
      s = s < 10 ? "0" + s : s;
      return y + "-" + MM + "-" + d + " " + h + ":" + m + ":" + s;
    },
    // 过滤企业列表
    formatList(data) {
      data.createDate = this.formatDate2Day(data.createDate);
      data.modifyDate = this.formatDate2Time(data.modifyDate);
      data.rechangeDate = this.formatDate2Time(data.rechangeDate);
      return data;
    },
  }
};
</script>
